<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\PayLogistics;

/**
 * PayLogisticsSearch represents the model behind the search form about `backend\models\PayLogistics`.
 */
class PayLogisticsSearch extends PayLogistics
{
    /**
     * @inheritdoc
     */
    public $logistics_company_name;
    public $trade_create_time;
    public function rules()
    {
        return [
            [['id', 'trade_id', 'item_id', 'number', 'logistics_state', 'admin_uid', 'admin_time'], 'integer'],
            [['item_memo', 'logistics_trade', 'logistics_no', 'logistics_message', 'logistics_name','logistics_company_name', 'send_address', 'send_photo', 'accept_address', 'accept_photo','operation_address','operation_photo','brand_name','user_name'], 'safe'],
            [['logistice_price'], 'number'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params,$financeDunning=false,$detail=false)
    {
    	$now = time();
       $condition=" pay_trade.trade_class=1 and pay_trade.create_time<{$now}-24*60*60 ";
        //如果是非管理员，则根据地址过滤
        if(Yii::$app->session['user_id']>0)
        {
             //运营商城市验证
            $user_id=Yii::$app->user->identity->user_id;
            if(intval($user_id)>0){
                $ifxgt=OperatorRelation::getifXat();//香港 澳门 台湾   直接in('台湾省','香港特别行政区','澳门特别行政区')
                $ifhascity=OperatorRelation::ifhascity();
                $ifhaszxsCountry=OperatorRelation::ifhaszxsCountry();
                $ifhascountry=OperatorRelation::ifhascountry();
                $ifhasprovince=OperatorRelation::ifhasprovince();
                if($ifhasprovince){
                    $provinceStr=OperatorRelation::getProvinceNameById();
                    $condition.=" and SUBSTR(SUBSTRING_INDEX(address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(address,' ',1))+1) in ({$provinceStr})";
                }
                if($ifhascity){
                    $cityStr=OperatorRelation::getCityNameByIdNprovincename($user_id);
                    if($ifhasprovince){
                        $condition.=" or SUBSTR(SUBSTRING_INDEX(address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(address,' ',1))+1) in ({$cityStr})";
                    }else{
                        $condition.=" and SUBSTR(SUBSTRING_INDEX(address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(address,' ',1))+1) in ({$cityStr})";
                    }
                }
                if($ifhaszxsCountry||$ifhascountry){
                    if($ifhasprovince||$ifhascity){
                        $a="or";
                    }else{
                        $a="and";
                    }
                    $countryStr=OperatorRelation::getcountryNameById();
                    $hascountryCondition=false;
                    if($ifhaszxsCountry){//有直辖市 也有区县 合并条件
                        if($ifhascountry){
                            $condition.=$a."  (SUBSTR(address,1,CHAR_LENGTH(SUBSTRING_INDEX(address,' ',2))) in ({$countryStr}) or SUBSTR(address,1,CHAR_LENGTH(SUBSTRING_INDEX(address,' ',3))) in ({$countryStr}))";
                        }else{
                            $condition.=$a."  SUBSTR(address,1,CHAR_LENGTH(SUBSTRING_INDEX(address,' ',2))) in ({$countryStr}) ";
                        }
                    }else{
                        if($ifhascountry){
                            $condition.=$a."  SUBSTR(address,1,CHAR_LENGTH(SUBSTRING_INDEX(address,' ',3))) in ({$countryStr})";
                        }
                    }
                }
            }
            
        }
        if ($financeDunning){
            $condition.=" and (ask_cost_price > payed or ask_cost_price = 0) AND logistics_state = 0 AND log_pay.trade_no IS NOT NULL";
        }
        $query = PayLogistics::find()
        ->joinWith(['iteminfo.brand_name','tradeinfo.userInfo','logisticsCompanies','tradeinfo.logPayInfoFirst'])
        ->where($condition)->select("pay_trade.price_state,pay_logistics.logistics_no,pay_logistics.id,pay_logistics.logistics_state,pay_logistics.trade_id,grp_brand.name brand_name, pay_trade.trade_no
                    ,pay_trade.create_time create_time,sys_item.brand_id,pay_logistics.logistics_name,pay_logistics.logistics_other_name");
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        //找到所有已付款，未发货的订单
        if ($financeDunning){
            $query->groupBy(['sys_item.brand_id','trade_id'])
            ->orderBy('trade_id ASC');
        }elseif ($detail){
            $query->orderBy('pay_trade.create_time DESC');
        }else{
            $query->groupBy(['sys_item.brand_id','trade_id'])
            ->orderBy('pay_trade.create_time DESC');
        }

        $dataProvider->Sort->attributes['trade_create_time'] = [
         	'asc' => ['pay_trade.create_time' => SORT_ASC],
        	'desc' => ['pay_trade.create_time' => SORT_DESC],
        ];
       
        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'trade_id' => $this->trade_id,
            'item_id' => $this->item_id,
            'number' => $this->number,
            'logistics_state' => $this->logistics_state,
            'logistice_price' => $this->logistice_price,
            'admin_uid' => $this->admin_uid,
            'admin_time' => $this->admin_time,
        ]);

        $query->andFilterWhere(['like', 'item_memo', $this->item_memo])
        	->andFilterWhere(['like', 'logistics_no', $this->logistics_no])
            ->andFilterWhere(['like', 'logistics_trade', $this->logistics_trade])
            ->andFilterWhere(['like', 'logistics_message', $this->logistics_message])
//             ->andFilterWhere(['like', 'logistics_name', $this->logistics_name])
            ->andFilterWhere(['like', 'grp_kuaidi.name', $this->logistics_company_name])
            ->andFilterWhere(['like', 'send_address', $this->send_address])
            ->andFilterWhere(['like', 'send_photo', $this->send_photo])
            ->andFilterWhere(['like', 'accept_address', $this->accept_address])
            ->andFilterWhere(['like', 'accept_photo', $this->accept_photo])
            ->andFilterWhere(['like', 'grp_brand.name', $this->brand_name])
            ->andFilterWhere(['like', 'user_info.username', $this->user_name]);

        return $dataProvider;
    }
    
    /*
     * 众筹采购管理
     */
    public function crowdsearch($params,$financeDunning=false,$detail=false)
    {
        $now = time();
        $condition="pay_trade.trade_class=2 and pay_trade.create_time<{$now}-24*60*60 ";
        //如果是非管理员，则根据地址过滤
        if(Yii::$app->session['user_id']>0)
        {
            //运营商城市验证
            $user_id=Yii::$app->user->identity->user_id;
            if(intval($user_id)>0){
                $ifxgt=OperatorRelation::getifXat();//香港 澳门 台湾   直接in('台湾省','香港特别行政区','澳门特别行政区')
                $ifhascity=OperatorRelation::ifhascity();
                $ifhaszxsCountry=OperatorRelation::ifhaszxsCountry();
                $ifhascountry=OperatorRelation::ifhascountry();
                $ifhasprovince=OperatorRelation::ifhasprovince();
                if($ifhasprovince){
                    $provinceStr=OperatorRelation::getProvinceNameById();
                    $condition.=" and SUBSTR(SUBSTRING_INDEX(address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(address,' ',1))+1) in ({$provinceStr})";
                }
                if($ifhascity){
                    $cityStr=OperatorRelation::getCityNameByIdNprovincename($user_id);
                    if($ifhasprovince){
                        $condition.=" or SUBSTR(SUBSTRING_INDEX(address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(address,' ',1))+1) in ({$cityStr})";
                    }else{
                        $condition.=" and SUBSTR(SUBSTRING_INDEX(address,' ',2),CHAR_LENGTH(SUBSTRING_INDEX(address,' ',1))+1) in ({$cityStr})";
                    }
                }
                if($ifhaszxsCountry||$ifhascountry){
                    if($ifhasprovince||$ifhascity){
                        $a="or";
                    }else{
                        $a="and";
                    }
                    $countryStr=OperatorRelation::getcountryNameById();
                    $hascountryCondition=false;
                    if($ifhaszxsCountry){//有直辖市 也有区县 合并条件
                        if($ifhascountry){
                            $condition.=$a."  (SUBSTR(address,1,CHAR_LENGTH(SUBSTRING_INDEX(address,' ',2))) in ({$countryStr}) or SUBSTR(address,1,CHAR_LENGTH(SUBSTRING_INDEX(address,' ',3))) in ({$countryStr}))";
                        }else{
                            $condition.=$a."  SUBSTR(address,1,CHAR_LENGTH(SUBSTRING_INDEX(address,' ',2))) in ({$countryStr}) ";
                        }
                    }else{
                        if($ifhascountry){
                            $condition.=$a."  SUBSTR(address,1,CHAR_LENGTH(SUBSTRING_INDEX(address,' ',3))) in ({$countryStr})";
                        }
                    }
                }
            }
            
        }
        if ($financeDunning){
            $condition.=" and (ask_cost_price > payed or ask_cost_price = 0) AND logistics_state = 0 AND log_pay.trade_no IS NOT NULL";
        }
        $query = PayLogistics::find()
        ->joinWith(['iteminfo.brand_name','tradeinfo.userInfo','logisticsCompanies','tradeinfo.logPayInfoFirst'])
        ->where($condition);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        //找到所有已付款，未发货的订单
        if ($financeDunning){
            $query->groupBy(['sys_item.brand_id','trade_id'])
            ->orderBy('trade_id ASC');
        }elseif ($detail){
            $query->orderBy('pay_trade.create_time DESC');
        }else{
            $query->groupBy(['sys_item.brand_id','trade_id'])
            ->orderBy('pay_trade.create_time DESC');
        }
        
        $dataProvider->Sort->attributes['trade_create_time'] = [
            'asc' => ['pay_trade.create_time' => SORT_ASC],
            'desc' => ['pay_trade.create_time' => SORT_DESC],
        ];
        
        $this->load($params);
        
        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }
        
        $query->andFilterWhere([
            'id' => $this->id,
            'trade_id' => $this->trade_id,
            'item_id' => $this->item_id,
            'number' => $this->number,
            'logistics_state' => $this->logistics_state,
            'logistice_price' => $this->logistice_price,
            'admin_uid' => $this->admin_uid,
            'admin_time' => $this->admin_time,
        ]);
        
        $query->andFilterWhere(['like', 'item_memo', $this->item_memo])
        ->andFilterWhere(['like', 'logistics_no', $this->logistics_no])
        ->andFilterWhere(['like', 'logistics_trade', $this->logistics_trade])
        ->andFilterWhere(['like', 'logistics_message', $this->logistics_message])
        //             ->andFilterWhere(['like', 'logistics_name', $this->logistics_name])
        ->andFilterWhere(['like', 'grp_kuaidi.name', $this->logistics_company_name])
        ->andFilterWhere(['like', 'send_address', $this->send_address])
        ->andFilterWhere(['like', 'send_photo', $this->send_photo])
        ->andFilterWhere(['like', 'accept_address', $this->accept_address])
        ->andFilterWhere(['like', 'accept_photo', $this->accept_photo])
        ->andFilterWhere(['like', 'grp_brand.name', $this->brand_name])
        ->andFilterWhere(['like', 'user_info.username', $this->user_name]);
        
        return $dataProvider;
    }
}
